ALTER PROCEDURE dbo.sp_GatherTrolley
AS
BEGIN
	SET NOCOUNT ON;
-- khai bao bien
	Declare @ID nvarchar(60)
	Declare @PlanID nvarchar(60)
	Declare @PrepareTime datetime
	Declare @Station nvarchar(10)
	Declare @MouldID nvarchar(10)
	Declare @MouldName nvarchar(20)
	Declare @Trolley nvarchar(10)
	Declare @Code nvarchar(10)
	Declare @OutPut int
	Declare @Outputtime datetime
	Declare @Marking nvarchar(1)
	Declare @GatherTrolley nvarchar(10)

	Declare @sql as nvarchar(1000)
	Declare @result as int

-- doc cac xe bi don len
	DECLARE CStatusGather2 CURSOR FOR
	SELECT  [GatherTrolley]
    FROM [dbo_ProcessorT] WHERE [StatusGather] = '2'
	
	begin tran compile_all

	OPEN CStatusGather2
	FETCH NEXT FROM CStatusGather2 INTO @GatherTrolley
	WHILE @@FETCH_STATUS = 0 
		BEGIN
		--------
		-- doc cac xe duoc lay ra de don
			DECLARE CStatusGather1 CURSOR FOR
			SELECT  [ID],[PlanID],[PrepareTime],[Station],[MouldID],[MouldName],
            [Trolley], [Code], [OutPut], [Outputtime], [Marking]
			FROM [dbo_ProcessorT] WHERE [StatusGather] = '1' AND [GatherTrolley] = @GatherTrolley

			OPEN CStatusGather1
			FETCH NEXT FROM CStatusGather1 INTO @ID, @PlanID, @PrepareTime, @Station, @MouldID,
								@MouldName, @Trolley, @Code, @OutPut, @Outputtime, @Marking
			WHILE @@FETCH_STATUS = 0 
				BEGIN 
	Declare @ID nvarchar(60)
	Declare @PlanID nvarchar(60)
	Declare @PrepareTime nvarchar(50)
	Declare @Station nvarchar(10)
	Declare @MouldID nvarchar(10)
	Declare @MouldName nvarchar(20)
	Declare @Trolley nvarchar(10)
	Declare @Code nvarchar(10)
	Declare @OutPut int
	Declare @Outputtime nvarchar(50)
	Declare @Marking nvarchar(1)
	Declare @GatherTrolley nvarchar(10)

	Declare @sql as nvarchar(1000)			
					set @sql = N'INSERT INTO  [GatherTrolleyHistory]([ID],[PlanID],[PrepareTime],[Station],' +
								'[MouldID],[MouldName],[Trolley],[Code],[OutPut],[Outputtime],[Marking])' +
								' VALUES (''+ @ID + '',''' + @PlanID + ''',''' + @PrepareTime + ''',''' + @Station + ''',''' + @MouldID + ''',''' + @MouldName + ''',''' + @Trolley + ''',''' + @Code + ''','' + @OutPut + '',''' + @Outputtime + ''',''' + @Marking + ''')'
			
	print @sql 
					exec sp_executesql @sql
					IF @@error <> 0 GOTO E_Compile_Fail
					FETCH NEXT FROM CStatusGather1 INTO @ID, @PlanID, @PrepareTime, @Station, @MouldID,
								@MouldName, @Trolley, @Code, @OutPut, @Outputtime, @Marking
				END			
			CLOSE CStatusGather1
			DEALLOCATE CStatusGather1
		--------	
		FETCH NEXT FROM CStatusGather2 INTO  @GatherTrolley
		END			
	CLOSE CStatusGather2 
	DEALLOCATE CStatusGather2 

CleanUp:
    return

E_Compile_Fail:
    declare @lerror int
    select @lerror = @@error
    rollback tran compile_all
    RAISERROR (@lerror,16,-1)
    goto CleanUp

END


--GO
exec sp_GatherTrolley
